package com.qidianit.mes.common;

import java.util.concurrent.*;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2025/7/22 10:52
 * @description 线程池工具类，用于统一管理线程资源
 */
public class ThreadPoolUtils {
    // 核心线程数
    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;

    // 最大线程数
    private static final int MAX_POOL_SIZE = 100;

    // 空闲线程存活时间
    private static final long KEEP_ALIVE_TIME = 60L;

    // 阻塞队列大小
    private static final int QUEUE_CAPACITY = 500;

    // 线程池实例
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(QUEUE_CAPACITY),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    /**
     * 提交Runnable任务
     * @param task 任务
     */
    public static void submit(Runnable task) {
        executor.submit(task);
    }

    /**
     * 提交Callable任务
     * @param task 任务
     * @return Future<T> 任务执行结果
     */
    public static <T> Future<T> submit(Callable<T> task) {
        return executor.submit(task);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        executor.shutdown();
    }

    /**
     * 获取当前线程池是否已关闭
     * @return boolean
     */
    public static boolean isShutdown() {
        return executor.isShutdown();
    }
}